<?php

/**
 * @author dungdhs@gmail.com
 * @copyright 2012
 */

function news_task(){
  return array(
    'admin' => array(
      'func'  => '_news_admin',
      'perm'  => 'admin news',
      'alias'	=> 'admin/news',
      'title' => 'QL Tin tức'
    ),
    
    'create' => array(
      'func'  => '_news_create',
      'perm'  => 'admin news create',
      'alias'	=> 'admin/news/create',
      'title' => 'Tạo tin mới'
    ),
    
    'edit' => array(
      'func'  => '_news_edit',
      'perm'  => 'admin news edit',
      'alias'	=> 'admin/news/edit',
      'title' => 'Sửa nội dung tin'
    ),
    
    'delete' => array(
      'func'  => '_news_delete',
      'perm'  => 'admin news delete',
      'alias'	=> 'admin/news/delete',
      'title' => 'Xóa tin'
    ),
    
    'detail' => array(
      'func'  => '_news_detail',
      'perm'  => 'news detail'
    ),
    
    'default' => array(
      'func'  => '_news_default',
      'perm'  => 'news detail',
      'alias'	=> 'tin-tuc',
      'title'	=> 'Tin tức'
    ),
    
    'follow' => array(
      'func'  => '_news_follow',
      'perm'  => 'logged user',
      'title'	=> 'Theo dõi tin'
    ),
    
    'like' => array(
      'func'  => '_news_like',
      'perm'  => 'logged user',
      'title'	=> 'Like tin'
    )
  );
}

function news_init(){
	theme_js(system_path('modules').'news/dz.news.js');
}

function _news_admin(){
  global $smarty, $database;
  
  $res = $database->db_query("SELECT * FROM news WHERE news_status=1 ORDER BY news_ispinned DESC, news_created DESC");
  $aNews= array();
  while ($news = $database->db_fetch_assoc($res)){
    $aNews[] = $news;
  }
  
  $smarty->assign('aNews', $aNews);
  $smarty->assign('aCat', __category_load('news'));
  
  return $smarty->fetch('news_admin.tpl');
}

function _news_create(){
	global $smarty, $database, $user;
	
	if (isset($_POST['news_title'])){
		$news_title			= PGRequest::getVar('news_title');
		$news_desc			= PGRequest::getVar('news_desc');
		$news_cat				= PGRequest::getVar('news_cat');
		$news_content		= PGRequest::getVar('news_content');		
		$news_cat_id		= PGRequest::getVar('news_cat_id');	
		$news_ismain		= PGRequest::getInt('news_ismain', 0);
		$news_published	= PGRequest::getInt('news_publish', 1);
		$news_ispinned	= PGRequest::getInt('news_ispinned', 0);
		$news_source		= PGRequest::getVar('news_source', 'Sưu tầm');
		$news_source_url= PGRequest::getVar('news_source_url');
		$news_thumb			= image_upload('news_thumb', false, $news_title);
		$news_youtube_url		= PGRequest::getVar('news_youtube_url');
		$news_youtube_id		= empty($news_youtube_url)?"":__youtube_id($news_youtube_url);
		
		$error = '';		
		
		$news_countdown		= PGRequest::getVar('news_countdown', 0);
		if ($news_countdown!=0){
			$news_countdown = strtotime($news_countdown);
			echo date('d/m/Y H:i', $news_countdown); exit();
		}
		
		$res = $database->db_query("INSERT INTO news(news_title, news_desc, news_thumb, news_content, news_cat_id, news_youtube_url, news_youtube_id, news_ismain, news_published, news_created, news_updated, news_creater, news_ispinned, news_source, news_source_url, news_countdown) VALUES ('%s', '%s', '%s', '%s', %d, '%s', '%s', %d, %d, %d, %d, %d, %d, '%s', '%s')", $news_title, $news_desc, $news_thumb, $news_content, $news_cat_id, $news_youtube_url, $news_youtube_id, $news_ismain, $news_published, time(), time(), $user->user_info['user_id'], $news_ispinned, $news_source, $news_source_url, $news_countdown);
		
		if ($res){
			PGTheme::set_message("Tạo thành công tin <strong><em>\"$news_title\"</em></strong>");
			$news_id = $database->db_insert_id();
    
	    $cat = __category_get($news_cat_id);
	    if ($cat){
	      url_set_alias('news/detail/'.$news_id, $cat['cat_title'].'/'.$news_title);
	    }else{
	      url_set_alias('news/detail/'.$news_id, $news_title);
	    }
	    cheader('news/create');
		}
		
		PGTheme::set_error("Có lỗi trong quá trình cập nhật, bạn vui lòng kiểm tra lại!");
	}
	
	__libs_ckeditor();
	__libs_pupload();
	__libs_datetimepicker();
	
	$smarty->assign('aCat', __category_load('news'));
	
	return $smarty->fetch('news_create.tpl');
}

function _news_detail(){
	global $database, $smarty, $user;
	
	$news_id = arg(2);
	$news = news_load($news_id);
	
	theme_title($news['news_title']);
	__ogp_set('og:image', l($news['news_thumb'], true));
  __ogp_set('og:description', strip_tags($news['news_desc']));
  __ogp_set('og:type', 'article');
  
	$newsRelate = array();
	$res = $database->db_query("SELECT * FROM news WHERE news_id<%d AND news_status=1 AND news_published=1 ORDER BY news_id DESC LIMIT 10", $news_id);
	while ($n = $database->db_fetch_assoc($res)){
		$newsRelate[] = $n;
	}
	
	if (sizeof($newsRelate)==0){
		$res = $database->db_query("SELECT * FROM news WHERE news_id>%d AND news_status=1 AND news_published=1 ORDER BY news_id ASC LIMIT 10", $news_id);
		while ($n = $database->db_fetch_assoc($res)){
			$newsRelate[] = $n;
		}
	}
	
	$smarty->assign('newsRelate', $newsRelate);
	$smarty->assign('news', $news);
	
	// UPDATE user doc tin
	if (!in_array($user->user_info['user_id'], array(7)))
		$database->db_query("INSERT INTO news_readers(news_id, user_id, created) VALUES (%d, %d, %d)", $news_id, $user->user_info['user_id'], time());
	
	// Tang luot doc tin
	$database->db_query("UPDATE news SET news_views=news_views+1 WHERE news_id=%d LIMIT 1", $news_id);
	
	$aReader = array();
	$res = $database->db_query("SELECT user_id FROM news_readers WHERE news_id=%d ORDER BY id DESC", $news_id);
	while ($u = $database->db_fetch_assoc($res)){
		$aReader[$u['user_id']] = $u['user_id']; 
	}
	
	$res = $database->db_query("SELECT user_avatar, user_fullname, user_id FROM users WHERE user_id IN (%s)", implode(',', $aReader));
	while ($u = $database->db_fetch_assoc($res)){
		$aReader[$u['user_id']] = array(
			'avatar'		=> $u['user_avatar'],
			'fullname'	=> $u['user_fullname']
		);
	}
	
	// Lay danh sach tin ban be doc
	$aFr = $user->getFollower();
	$aFrNews = array();
	if (count($aFr)){
		$res = $database->db_query("SELECT * FROM news_readers WHERE user_id IN (%s) AND news_id!=%d ORDER BY created DESC  LIMIT 0, 9", implode(',', $aFr), $news_id);
		while ($n = $database->db_fetch_assoc($res)){
			$aFrNews[$n['news_id']] = $n['news_id'];
		}
		
		if (count($aFrNews)>0){
			$res = $database->db_query("SELECT news_title, news_id, news_thumb FROM news WHERE news_id IN (%s) AND news_status=1 AND news_published=1");
			while ($n = $database->db_fetch_assoc($res)){
				$aFrNews[$n['news_id']] = $n;
			}
			
			foreach ($aFrNews as $id=>$val)
			if (!is_array($val)) unset($aFrNews[$id]);
		}
	}
	$smarty->assign('aFrNews', $aFrNews);
	
	$smarty->assign('aReader', $aReader);
	
	PGTheme::$pageTemplate = 'nowrap';
	return $smarty->fetch('news_detail.tpl');
}

function _news_edit(){
	global $smarty, $database, $user;
	
	$news_id = arg(2, 0);	
	$news = news_load($news_id);
	if (!$news){
		cheader('news/admin');
	}
	
	if (isset($_POST['news_title'])){
		$news_title			= PGRequest::getVar('news_title');
		$news_desc			= PGRequest::getVar('news_desc');
		$news_content		= PGRequest::getVar('news_content');		
		$news_cat_id		= PGRequest::getVar('news_cat_id');
		$news_ismain		= PGRequest::getInt('news_ismain', 0);
		$news_published	= PGRequest::getInt('news_publish', 1);
		$news_ispinned	= PGRequest::getInt('news_ispinned', 0);		
		$news_source		= PGRequest::getVar('news_source', 'Sưu tầm');
		$news_source_url= PGRequest::getVar('news_source_url');
		$news_thumb			= image_upload('news_thumb', false, $news_title);
		$news_youtube_url		= PGRequest::getVar('news_youtube_url');
		$news_youtube_id		= empty($news_youtube_url)?"":__youtube_id($news_youtube_url);
		if (!$news_thumb){ 
			$news_thumb = $news['news_thumb'];
		}else{
			@unlink($news['news_thumb']);
		}
		
		$news_countdown		= PGRequest::getVar('news_countdown', 0);
		if ($news_countdown!=0){
			$news_countdown = strtotime($news_countdown);
		}
		
		$res = $database->db_query("UPDATE news SET news_title='%s', news_desc='%s', news_content='%s', news_cat_id=%d, news_youtube_url='%s', news_youtube_id='%s', news_ismain=%d, news_published=%d, news_thumb='%s', news_updated=%d, news_ispinned=%d, news_source='%s', news_source_url='%s', news_countdown=%d WHERE news_id=%d LIMIT 1", $news_title, $news_desc, $news_content, $news_cat_id, $news_youtube_url, $news_youtube_id, $news_ismain, $news_published, $news_thumb, time(), $news_ispinned,$news_source, $news_source_url, $news_countdown, $news_id);
		 
		PGTheme::set_message('Cập nhật thành công!'); 
    cheader('news/admin');
	}
	
	$smarty->assign('news', $news);
	
	__libs_ckeditor();	
	__libs_datetimepicker();
	
	PGTheme::$pageTemplate = 'admin';
	
	$smarty->assign('aCat', __category_load('news'));
	
	return $smarty->fetch('news_edit.tpl');
}

function _news_delete(){
	global $database;
	
	$news_id = arg(2);
	$news = news_load($news_id);
	
	if (!$news){
		PGTheme::set_error("Tin bạn chọn không tồn tại.");
		cheader('news/admin');
	}
	
	$database->db_query("UPDATE news SET news_status=0 WHERE news_id=%d LIMIT 1", $news_id);
	
	PGTheme::set_message("Xóa thành công tin <em>\"{$news['news_title']}\"</em>");
	cheader('news/admin');
}

function _news_default(){
	global $database, $smarty, $variable;
	
	$aCat = array(1, 3, 4);
	$aNews = array();
	
	PGTheme::$pageTemplate = 'newsmain';
	
	foreach ($aCat as $cat_id){
		$res = $database->db_query("SELECT * FROM news WHERE news_cat_id=%d AND news_ismain=1 AND news_status=1 AND news_published=1 ORDER BY news_updated DESC LIMIT 1;", $cat_id);
		while ($news = $database->db_fetch_assoc($res)){
			$aNews[$news['news_cat_id']] = $news;
		}
	}
	
	$newsEmspo = array();
	$res = $database->db_query("SELECT * FROM news WHERE news_cat_id=2 AND news_ismain=1 AND news_status=1 AND news_published=1 ORDER BY news_updated DESC LIMIT 6;");
	while ($news = $database->db_fetch_assoc($res)){
		$newsEmspo[] = $news;
	}
	
	$res = $database->db_query("SELECT * FROM videos WHERE video_status=1 AND video_published=1 ORDER BY video_updated DESC LIMIT 1");
	$video = $database->db_fetch_assoc($res);
	
	$smarty->assign('news_banner_link', $variable->get('news_banner_link'));
	$smarty->assign('news_banner_title', $variable->get('news_banner_title'));
	$smarty->assign('news_banner_desc', $variable->get('news_banner_desc'));
	$smarty->assign('news_banner', $variable->get('news_banner'));
	$smarty->assign('news_banner_right', $variable->get('news_banner_right'));
	$smarty->assign('news_banner_right_link', $variable->get('news_banner_right_link'));
	
	$smarty->assign('aNews', $aNews);
	$smarty->assign('newsEmspo', $newsEmspo);
	$smarty->assign('video', $video);
	$smarty->assign('aCat', __category_load('news'));
	
	return $smarty->fetch('news_default.tpl');
}

function news_load($news_id){
	global $database;
	
	$res = $database->db_query("SELECT * FROM news WHERE news_id=%d", $news_id);
	return $database->db_fetch_assoc($res);
}

function _news_follow(){
	global $database, $user;
	
	$news_id	= PGRequest::getInt('news_id', 0);
	$task			= PGRequest::getVar('task', 'follow');
	
	
	$news	= news_load($news_id);
	if (!$news){
		system_json(array(
			'code'		=> 0,
			'mess'		=> 'Tin tức không tồn tại!'
		));
	}
	
	if ($task=='follow'){
		$res = $database->db_query("INSERT INTO news_followers(news_id, user_id, created) VALUES (%d, %d, %d)", $news_id, $user->user_info['user_id'], time());
	}else{
		$res = $database->db_query("DELETE FROM news_followers WHERE news_id=%d AND user_id=%d", $news_id, $user->user_info['user_id']);
	}
	
	system_json(array(
		'code'		=> 1
	));
}

function _news_like(){
	global $database, $user;
	
	$news_id	= PGRequest::getInt('news_id', 0);
	$task			= PGRequest::getVar('task', 'follow');
	
	$news	= news_load($news_id);
	if (!$news){
		system_json(array(
			'code'		=> 0,
			'mess'		=> 'Tin tức không tồn tại!'
		));
	}
	
	if ($task=='follow'){
		$res = $database->db_query("INSERT INTO news_likes(news_id, user_id, created) VALUES (%d, %d, %d)", $news_id, $user->user_info['user_id'], time());
		if ($res){
			$database->db_query("UPDATE news SET news_like=news_like+1 WHERE news_id=%d", $news_id);
		}
	}else{
		$res = $database->db_query("DELETE FROM news_likes WHERE news_id=%d AND user_id=%d", $news_id, $user->user_info['user_id']);
		if ($res){
			$database->db_query("UPDATE news SET news_like=news_like-1 WHERE news_id=%d", $news_id);
		}
	}
	
	system_json(array(
		'code'		=> 1
	));
}

function __news_follower($user_id=false){
	global $database, $user;
	
	if (!$user_id) $user_id = $user->user_info['user_id'];
	
	$aFollow = array();
	$res = $database->db_query("SELECT * FROM news_followers WHERE user_id=%d", $user_id);
	while ($nf = $database->db_fetch_assoc($res)){
		$aFollow[] = $nf['news_id'];
	}
	
	theme_js('dz.news.updateFollow('.json_encode($aFollow).');');
	
	return $aFollow;
}

function __news_like($user_id=false){
	global $database, $user;
	
	if (!$user_id) $user_id = $user->user_info['user_id'];
	
	$aLike = array();
	$res = $database->db_query("SELECT * FROM news_likes WHERE user_id=%d", $user_id);
	while ($nf = $database->db_fetch_assoc($res)){
		$aLike[] = $nf['news_id'];
	}
	
	theme_js('dz.news.updateLike('.json_encode($aLike).');');
	
	return $aLike;
}